/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package impresos;

import java.awt.Component;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.print.*;
import java.awt.print.PrinterJob;
import java.awt.print.PageFormat;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.swing.JTable;
import otros.Configuracion;
import otros.Util;
import tablasSql.ConsultaBD;
import tablasSql.FacturasAlbaranes;

/**
 *
 * @author FERRETERIA
 */


class ObjetoDeImp347 extends Component implements Printable{
    
    private DatosToImprimir d;
    int posY;
    int NUM_LINEAS;
    
    public ObjetoDeImp347 (DatosToImprimir d, int tamLineas) {
        super();
        NUM_LINEAS = tamLineas;
        this.d = d;
    } 
    
    
    private int getIniPosX() { 
       return 56;
    }
        
    public void EncabezadoA4(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
         
        int y = 10;
        posY = 80;
        int posX = getIniPosX();
        
        g.setFont(new Font ("Calibri", Font.BOLD, 16));
        g.drawString("Modelo 347 del año " + d.getFecha(), posX, posY);      // x,y
        g.setFont(new Font ("Calibri", Font.PLAIN, 12));
        
        g.drawLine(posX, posY +=5, 540, posY);
    }
    
    
    
    private int getDespazamiento(int i) {
        switch (i) {
            case 1:
                return 255;
            
            case 99: 
                return 170;
            case 100:
                return 315;
            default:
                return 50;
        }
    }
    
    private String FormatoDinero(FontMetrics fm,String num) {
        String result = "";
        int numDigit = 11;
        switch(fm.getFont().getSize()) {
           case 10: numDigit = 11;
               break;
           case 12: numDigit = 9;
               break;            
       }
        for (int i = 0; i < numDigit - num.length(); i++) {
            result += " "; 
        }
        result += num;
        return result;
    }
    
    public void Datos(Graphics g) {
        int posX = getIniPosX();
        int y;
        
        JTable tabla = d.getTabla();
        
        posY += 13;
        int x = 0;
        g.setFont(new Font ("Calibri", Font.BOLD, 12));
        for (int i = 0; i < tabla.getColumnCount(); i++) {
            g.drawString(tabla.getColumnName(i), posX + x, posY);
            x += getDespazamiento(i);
        }
        
        y = 14;
        posY += y;
        
        int j = 0;
        for (int i = (d.getPagina() * NUM_LINEAS)/6; (i < tabla.getRowCount()) && 
                (i * 6 + 6  < (d.getPagina()+1) * NUM_LINEAS); ++i) {
            g.setFont(new Font ("Calibri", Font.PLAIN, 10));
            x = 0;
            for (int k = 0; k < tabla.getColumnCount()-1; k++) {
                String valor = String.valueOf(tabla.getValueAt(i, k));
                if (valor.equals("0")) {
                    posY += y*j;
                    return;
                }
                g.drawString(valor, posX + x, posY + y * j);
                x += getDespazamiento(k);
            }
            x = getDespazamiento(99);
            g.setFont(new Font ("Consolas", Font.PLAIN, 10));
            Float [] trim = FacturasAlbaranes.getTrimestres(Integer.parseInt(d.getTipoTicket()),""+tabla.getValueAt(i, 0), d.getFecha());
            g.drawString("Trimestre 1: ", posX + x, posY + y * (++j));
            g.drawString(FormatoDinero(g.getFontMetrics(g.getFont()), Util.getFormatPrecio(trim[0], 2)), 
                                posX + getDespazamiento(100), posY + y * j);
            g.drawString("Trimestre 2: ", posX + x, posY + y * (++j));
            g.drawString(FormatoDinero(g.getFontMetrics(g.getFont()), Util.getFormatPrecio(trim[1], 2)), 
                                posX + getDespazamiento(100), posY + y * j);
            g.drawString("Trimestre 3: ", posX + x, posY + y * (++j));
            g.drawString(FormatoDinero(g.getFontMetrics(g.getFont()), Util.getFormatPrecio(trim[2], 2)), 
                                posX + getDespazamiento(100), posY + y * j);
            g.drawString("Trimestre 4: ", posX + x, posY + y * (++j));
            g.drawString(FormatoDinero(g.getFontMetrics(g.getFont()), Util.getFormatPrecio(trim[3], 2)), 
                                posX + getDespazamiento(100), posY + y * j);
            
            g.setFont(new Font ("Consolas", Font.BOLD, 12));
            g.drawString(FormatoDinero(g.getFontMetrics(g.getFont()), Util.getFormatPrecio(Float.parseFloat(""+tabla.getValueAt(i, 2)),2)), 
                                posX + getDespazamiento(100), posY + y * ++j);
            j++;
        } 
        posY += y*j;
    }
    
    public void Pie(Graphics g) {
         
    }
               
    public int print(Graphics g, PageFormat f, int pageIndex){
        if (d.getTotalPaginas() > pageIndex) {
           d.setPagina(pageIndex % d.getTotalPaginas()); 
           EncabezadoA4(g);
           Datos(g); 
           //Pie(g);
           return PAGE_EXISTS;
        }
        else
            return NO_SUCH_PAGE;
    }
}

public class Imp347 {
    
    static final int NUM_LINEAS = 49;
    static String impresora;
    
    void Imprimir () {
        setImpresora(false);
    }
    
    static void setImpresora (boolean pdf) {
        if (pdf)
            impresora = Configuracion.getInstance().getProperty(Configuracion.IMP_PDF);
        else
            impresora = Configuracion.getInstance().getProperty(Configuracion.IMP_NORMAL);
    }
    
    static public void imprime(boolean pdf, DatosToImprimir d){
        ConsultaBD.cursorEspera(null);
        setImpresora(pdf);
        PrinterJob job = PrinterJob.getPrinterJob();
        PageFormat pf = job.defaultPage();
        Paper paper = new Paper();
        double margin;
        paper.setSize(595.0,842.0); // ancho y alto  A4
        margin = 10;
        
        
        paper.setImageableArea(margin, margin, paper.getWidth()-margin, paper.getHeight()-margin);
        pf.setPaper(paper);
        pf.setOrientation(PageFormat.PORTRAIT);  // vertical
        job.setJobName("Mod347 " + d.getFecha());
        
        PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
        for (PrintService printService : services) {
            if (printService.getName().equals(impresora)) {
                try {
                    job.setPrintService(printService);
                    break;
                } catch (PrinterException ex) {
                    System.out.println(ex);
                }
            }
        }
        try{
            int tamLista = d.getTabla().getRowCount() * 6;
            int hojas = tamLista/NUM_LINEAS;
            if (tamLista%NUM_LINEAS == 0)
               hojas--;
            d.setTotalPaginas(hojas);      
            job.setPrintable(new ObjetoDeImp347(d, NUM_LINEAS), pf);  
            job.print();
        } catch(PrinterException e){
             System.out.println(e);
        }

        ConsultaBD.cursorNormal(null);
    }
}
